<template>
    <view class="smslogin-index">
        <view>
            <view class="smslogin-index-title">
                <view class="smslogin-index-title-sms">验证码登录</view>
                <view class="smslogin-index-title-huanying">未注册的手机号将自动创建账号</view>
            </view>
            <view class="smslogin-index-title-content">
                <u--form labelPosition="left" :model="model1" :rules="rules" ref="uForm">
                    <u-form-item label=" " prop="phone" borderBottom ref="item1">
                        <view class="smslogin-index-title-content-text">
                            <u--input border="none" type="number" v-model="model1.phone" maxlength='11'
                                prefixIcon="/static/img/login/phone.png" placeholder="请输入手机号" clearable
                                placeholder-class="title_input" prefixIconStyle="width: 11px;height: 16px"></u--input>
                        </view>
                    </u-form-item>
                    <view class="smslogin-index-title-content-div">
                    </view>
                    <u-form-item label=" " prop="captcha" borderBottom ref="item1">
                        <u--input maxlength="10" border="none" type="number" clearable placeholder="请输入验证码"
                            prefixIcon="/static/img/login/dunpai.png" prefixIconStyle="width: 14px;height: 16px"
                            v-model="model1.captcha" placeholder-class="title_input"></u--input>
                        <text slot="right" class="smslogin-index-input-captcha-captcha" @click="onGetCode"
                            :class="{ 'disabled': countdown > 0 }">{{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码'
                            }}</text>
                    </u-form-item>
                </u--form>
            </view>
            <button class="smslogin-index-button-login" @click="login">手机登录</button>
            <view class="login_index_tabs">
                <view class="account" @click="mobileLogin">
                    <image class="accounts" src="https://dujiaojing.oss-cn-huhehaote.aliyuncs.com/uploads/2025/7/29/1753778031678_7bfca000/account.png?x-oss-process=image/resize,w_300" alt=""></image>
                    <view>学号登录</view>
                </view>
                <view class="account">
                    <image class="phone" src="https://dujiaojing.oss-cn-huhehaote.aliyuncs.com/uploads/2025/7/29/1753778044521_f4470e37/phone1.png?x-oss-process=image/resize,w_300" alt=""></image>
                    <view>手机登录</view>
                </view>
            </view>
        </view>
        <!-- 隐私政策 -->
        <view class="smslogin-index-policy">
            <u-checkbox-group slot="right" v-memo="checkedArr" @change="checkboxChange" class="agreement_radio">
                <u-checkbox size='35' shape="circle"></u-checkbox>
            </u-checkbox-group>
            <view class="smslogin-index-policy-text">
                <text>我已阅读并同意</text>
                <view class="smslogin-index-policy-text-rules" @click="goRules">《用户协议》</view>
                <text>和</text>
                <view class="smslogin-index-policy-text-rules" @click="goRules">《隐私政策》</view>
            </view>
        </view>
    </view>
</template>

<script>
import {
    encrypt,
    phoneLogin,
    getInfo,
    apiLogin,
    getPhoneCode
} from '@/api/index.js'
import debounce from 'lodash/debounce';
export default {
    data() {

        return {
            // 手机号
            phone: '',
            // 选中值
            checkVal: '0',
            // 选中状态
            checked: false,
            checkedArr: [],
            // 验证码
            captcha: '',
            countdown: 0, // 倒计时秒数
            timer: null, // 计时器
            model1: {
                captcha: '',
                phone: '',
            },
            rules: {
                phone: [{
                    type: 'string',
                    required: true,
                    message: '请填写手机号码',
                    trigger: ['blur', 'change']
                },
                {
                    pattern: /^1[3456789]\d{9}$/,
                    message: '请输入有效的手机号码',
                    trigger: 'blur'
                },
                ],
                captcha: [{
                    type: 'string',
                    required: true,
                    message: () => {
                        return this.countdown > 0 ? '请填写验证码' : '请先获取右侧验证码'
                    },
                    trigger: ['blur', 'change']
                },
                {
                    pattern: /^[0-9]*$/,
                    message: '请填写正确数字验证码',
                    trigger: 'blur'
                },
                ],
            }
        }
    },
    onShow() {

    },
    onLoad() { },
    methods: {
        // 账号登录
        mobileLogin() {
            uni.navigateTo({
                url: "/subpackage1/login/account"
            })
        },
        // 隐私政策勾选
        checkboxChange(e) {
            this.checked = e.length > 0;
        },
        onGetCode: debounce(function () {
            this.getCode()
        }, 500),
        // 获取验证码
        getCode() {
            this.$refs.uForm.validateField('phone', (errorsRes) => {
                if (errorsRes.length === 0) {
                    // 如果倒计时还在进行中或手机号不合法，则不执行获取验证码操作
                    if (this.countdown > 0) {
                        uni.$u.toast('验证码已发送，请勿重复点击');
                        return
                    }
                    getPhoneCode({
                        phone: this.model1.phone,
                    }).then((res) => {
                        // 假设后端返回成功后开始倒计时
                        this.startCountdown();
                    })
                }
            })
        },
        // 倒计时
        startCountdown() {
            this.countdown = 60; // 设置倒计时时间为60秒
            this.timer = setInterval(() => {
                if (this.countdown > 0) {
                    this.countdown--;
                } else {
                    clearInterval(this.timer);
                    this.timer = null;
                }
            }, 1000);
        },
        // 登录
        login() {
            this.$refs.uForm.validate().then(valid => {
                if (valid) {
                    // 是否勾选隐私政策
                    if (!this.checked) {
                        uni.showToast({
                            title: '请阅读并勾选隐私政策',
                            icon: 'none'
                        });
                        // return;
                    } else {
                        phoneLogin({
                            phonenumber: this.model1.phone,
                            smsCode: this.model1.captcha,
                            type: 0, // 必传code
                            clientId: '428a8310cd461950ue699df5d894f886',
                            grantType: "sms",
                            tenantId: "000000",
                        }).then((res) => {
                            if (res.code == 200) {
                                uni.setStorageSync('token', res.data.access_token);
                                if (res.data.access_token) {
                                    getInfo().then(res => {
                                        if (res.data.user.roles[0].roleKey === 'student' || res.data.user.roles[0].roleKey === 'teacher') {
                                            // 有圈子
                                            if (res.data.user.circleCategory) {
                                                uni.setStorageSync('userName', res.data.user.nickName);
                                                uni.setStorageSync('deptName', res.data.user.deptName);
                                                uni.switchTab({
                                                    url: "/pages/tabbar/home/home"
                                                })
                                            } else {
                                                uni.setStorageSync('userName', res.data.user.nickName);
                                                uni.setStorageSync('deptName', res.data.user.deptName);
                                                uni.navigateTo({
                                                    url: "/subpackage1/login/circle"
                                                })
                                            }
                                        } else {
                                            uni.removeStorageSync('token')
                                            uni.showToast({
                                                title: '无权限登录',
                                                icon: 'none', //将值设置为 success 或者 ''
                                                duration: 2000 //持续时间为 2秒
                                            })
                                        }
                                    })
                                } else {
                                    uni.switchTab({
                                        url: "/pages/tabbar/home/home"
                                    })
                                }
                            } else {
                                uni.showToast({
                                    title: res,
                                    icon: 'none', //将值设置为 success 或者 ''
                                    duration: 2000 //持续时间为 2秒
                                })
                            }
                        })
                    }
                } else {
                    return false;
                }
            });
        },
        // 隐私政策跳转
        goRules() {
            uni.navigateTo({
                url: '/subpackage1/login/policy'
            })
        },
        // 账户密码登录
        goSms() {
            uni.navigateBack({
                delta: 1
            });
        },
        // 手机号快捷登录
        onGetPhoneNumber(e) {
            if (e.detail.errMsg === "getPhoneNumber:fail user deny") {
                // 处理用户拒绝授权的情况
            } else {
                if (!this.checked) {
                    uni.showToast({
                        title: '请阅读并勾选惠麦供应链管理系统隐私政策',
                        icon: 'none'
                    });
                } else {
                    this.getphonenumber(e);
                    uni.showToast({
                        title: "登录中...",
                        mask: true,
                        icon: 'loading', //将值设置为 success 或者 ''
                        duration: 5000 //持续时间为 2秒
                    })

                }
            }
        },
        // 快捷登录授权后登录
        getphonenumber(e) {
            // encrypt({
            // 	code: e.detail.code
            // }).then(res => {
            // 	if (res.code == 200) {
            // 		// 无码登录
            // 		phoneLogin({
            // 			phone: JSON.parse(res.msg).phone_info.purePhoneNumber,
            // 			code: '',
            // 			type: 1, // 1 不必传code
            // 			clientId: '428a8310cd461950ue699df5d894f886'
            // 		}).then(response => {
            // 			if (response.code == 200) {
            // 				uni.setStorageSync('clientId', response.data.client_id);
            // 				uni.setStorageSync('phoneName', response.data.phone);
            // 				uni.setStorageSync('token', response.data.access_token);
            // 				if (response.data.access_token) {
            // 					getInfo().then(res => {
            // 						if (res.data.supplier) {
            // 							uni.setStorageSync('supplierName', res.data.supplier.supplierName);
            // 							uni.setStorageSync('supplierId', res.data.supplier.id);
            // 							uni.switchTab({
            // 								url: "/pages/index/index"
            // 							})
            // 						} else {
            // 							uni.switchTab({
            // 								url: "/pages/index/index"
            // 							})
            // 						}
            // 					})
            // 				} else {
            // 					uni.switchTab({
            // 						url: "/pages/index/index"
            // 					})
            // 				}
            // 			} else {
            // 				uni.showToast({
            // 					title: res,
            // 					icon: 'none', //将值设置为 success 或者 ''
            // 					duration: 2000 //持续时间为 2秒
            // 				})
            // 			}
            // 		})
            // 	} else {
            // 		uni.showToast({
            // 			title: JSON.parse(res.msg).errmsg,
            // 			icon: 'none'
            // 		});
            // 	}
            // })
        },
    },
    onReady() {
        //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
        this.$refs.uForm.setRules(this.rules)
    },

}
</script>

<style lang="less" scoped>
.smslogin-index {
    display: flex;
    flex-flow: column;
    justify-content: space-between;
    padding-bottom: 30px;
    box-sizing: border-box;
    width: 100%;
    height: 100vh;

    .smslogin-index-title {
        .smslogin-index-title-sms {
            margin: 218rpx 0 30rpx 50rpx;
            color: #1A1B1C;
            font-size: 42rpx;
            font-weight: Semibold;
        }

        .smslogin-index-title-huanying {
            margin: 0 0 102rpx 50rpx;
            color: #C0C6D0;
            font-size: 28rpx;
            font-weight: Regular;
        }
    }

    .smslogin-index-input {
        .smslogin-index-input-phoneNumber {
            display: flex;
            align-items: center;
            border-bottom: 2rpx #EDEDED solid;
            padding: 32rpx 0;
            margin: 0 50rpx;



            input {
                -webkit-user-select: none;
                /* Safari */
                -moz-user-select: none;
                /* Firefox */
                -ms-user-select: none;
                /* IE10+/Edge */
                user-select: none;
                /* Standard syntax */

                /* 去掉边框 */
                outline: none;
                margin-left: 20rpx;

                /deep/.title_input {
                    color: #B8BECA;
                }
            }
        }

        .smslogin-index-input-captcha {
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 2rpx #EDEDED solid;
            padding: 32rpx 0;
            margin: 0 50rpx;

            input {
                -webkit-user-select: none;
                /* Safari */
                -moz-user-select: none;
                /* Firefox */
                -ms-user-select: none;
                /* IE10+/Edge */
                user-select: none;
                /* Standard syntax */

                /* 去掉边框 */
                outline: none;

                /deep/.title_input {
                    color: #B8BECA;
                }
            }


        }
    }

    .smslogin-index-button-login {
        width: 90%;
        border-radius: 48rpx;
        background-color: rgb(34, 175, 229);
        color: #FFFFFF;
        margin-top: 98rpx;
    }

    .login_index_tabs {
        font-weight: 400;
        font-size: 14px;
        line-height: 14px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        align-items: center;
        margin-top: 30px;
        padding-left: 50rpx;
        padding-right: 50rpx;

        .account {
            color: #C0C6D0;
            font-size: 24rpx;
            display: flex;
            align-items: center;

            image {
                margin-right: 10rpx;
            }

            .accounts {
                width: 26rpx;
                height: 27rpx;
            }

            .phone {
                width: 18rpx;
                height: 26rpx;
            }
        }

    }

    .smslogin-index-policy {
        margin-top: 54rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .agreement_radio {
            margin-left: 60rpx;
        }

        .smslogin-index-policy-text {
            display: flex;
            align-items: center;
            font-size: 24rpx;

        }
    }
}

/deep/.u-form-item__body__left__content__label {
    display: none !important;
}

/deep/.u-form-item__body__right {
    width: 400rpx !important;
}

/deep/.u-input__content__field-wrapper__field {
    font-size: 30rpx !important;
}

.smslogin-index-input-phoneNumber-86 {
    // font-size: 32rpx;
    // font-weight: Regular;
    padding-right: 20rpx;
    width: 22rpx;
    height: 32rpx;

    image {
        width: 22rpx;
        height: 32rpx;
    }
}

.smslogin-index-input-captcha-captcha {
    padding-left: 20rpx;
    font-size: 32rpx;
}

/deep/.u-form-item__body__left {
    display: none !important;
}

.smslogin-index-title-content {
    padding-left: 50rpx;
    padding-right: 50rpx;
}

.smslogin-index-title-content-text {
    display: flex;
}

.smslogin-index-title-content-div {
    height: 40rpx;
    width: 100%;
}
</style>